<template>
    <div class="box_bg">
        <h2 class="box_tit">
            <i class="icon icon1"></i>
            <template  v-if="this.$route.query.id != undefined">用户管理/编辑</template>
            <template  v-if="this.$route.query.id == undefined">用户管理/添加</template>
            <i class="reti"></i>
        </h2>
        <!-- <div class="blank20"></div> -->
        <!-- 页面编辑页*****开始 -->
        <div class="goBack">
            <a href="JavaScript:void(0);" class="btns" @click="goBack"><i class="iconfont icon-fanhui"></i> 返回上一级</a>
        </div>
        <div class="components_edit user_edit_box">
            <!-- 表单开始 -->
            <el-form ref="userForm" :model="userForm" :rules="rules" :inline="true" label-width="100px">
                <el-form-item label="姓名：" prop="name">
                    <el-input v-model="userForm.name" placeholder="请填写账户名" :disabled="this.$route.query.type == '2'"></el-input>
                </el-form-item>
                <el-form-item label="性别：">
                    <el-radio-group v-model="userForm.sex">
                        <el-radio :label="0">男</el-radio>
                        <el-radio :label="1">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="所属机构：" prop="managermentCenterName" class="is-required org_box">
                    <div class="zTree_box model_ct">
                        <div id="thrTree1" style="display: none;">
                            <ul class="ztree orgTree1" id="orgTree1"></ul>
                        </div>
                    </div>
                    <div @click="showMenu" class="el-input__inner textcol">{{managermentCenterName}}</div>
                    <div class="el-form-item__error" style="display: none;">
                        请选择所属机构
                      </div>
                    <!-- <el-input v-model="managermentCenterName" placeholder="请填写所属机构" @focus="showMenu"></el-input> -->
                </el-form-item>
                <el-form-item label="专业组：" prop="professionGroup">
                    <el-select v-model="userForm.professionGroup" placeholder="请选择专业组" value-key="value" filterable>
                        <el-option v-for="item in selectOptions.professionGroup" :key="item.id" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="民族："  prop="nation">
                    <el-select v-model="userForm.nation" placeholder="请选择民族" filterable>
                        <el-option v-for="item in selectOptions.nationList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="政治面貌：" prop="politicalStatus">
                    <el-select v-model="userForm.politicalStatus" placeholder="请选择政治面貌" filterable>
                        <el-option v-for="item in selectOptions.politicalStatus" :key="item.value" :label="item.label" :value="item.value">{{item.label}}</el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="生日：" prop="birthdate">
                    <el-date-picker v-model="userForm.birthdate" type="date" placeholder="请填写生日"></el-date-picker>
                </el-form-item>
                <el-form-item label="身份证：" prop="idcard">
                    <el-input v-model="userForm.idcard" placeholder="请填写身份证"></el-input>
                </el-form-item>
                <el-form-item label="邮箱：" prop="email">
                    <el-input v-model="userForm.email" placeholder="请填写邮箱"></el-input>
                </el-form-item>
                <el-form-item label="电话：" prop="mobile">
                    <el-input type="tel" v-model="userForm.mobile" placeholder="请填写电话号码"></el-input>
                </el-form-item>
                <el-form-item label="最高学历：" prop="educational">
                    <el-input v-model="userForm.educational" placeholder="请填写最高学历"></el-input>
                </el-form-item>
                <el-form-item label="学位：" prop="degree">
                    <el-input v-model="userForm.degree" placeholder="请填写学位"></el-input>
                </el-form-item>
                <el-form-item label="毕业学校：" prop="graduationSchool">
                    <el-input v-model="userForm.graduationSchool" placeholder="请填写毕业学校"></el-input>
                </el-form-item>
                <el-form-item label="所学专业：" prop="profession">
                    <el-input v-model="userForm.profession" placeholder="请填写所学专业"></el-input>
                </el-form-item>
                <el-form-item label="状态：" prop="state">
                    <el-radio-group v-model="userForm.state">
                        <el-radio :label="1">在职 </el-radio>
                        <el-radio :label="2">离职</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="入职时间：" prop="workTime">
                    <el-date-picker v-model="userForm.workTime" type="date" placeholder="请选择入职时间"></el-date-picker>
                </el-form-item>
                <!-- <el-form-item label="用户密码：" prop="password" v-if="this.$route.query.id == undefined">
                    <el-input v-model="userForm.password" placeholder="请填写用户密码"></el-input>
                </el-form-item> -->
            </el-form>

            <div class="components_handle_btns">
                <el-button  class="btns" @click="addSubmit('userForm',$event)" type="text" size="small">确定</el-button>
                <el-button  class="btns cancel" @click="userResetQuery()" type="text" size="small">重置</el-button>
            </div>
        </div>
        <!-- 页面编辑页*****开始 -->
    </div>

</template>

<script>
import {
  officesTreeUrl,
  getUserUrl,
  officesUserIdUrl,
  officesIdUserUrl,
  officesIdUrl,
  usersUrl,
  userInsertUrl,
  dictsTypesSubListUrl,
  usersHandleUrl
} from "../../../axios/api.js";
import vbootstrapStyle from "../../../../static/css/bootstrapStyle.css";
import vZtreeCore from "../../../../static/js/jquery.ztree.core.js";
import vZtreeExcheck from "../../../../static/js/jquery.ztree.excheck.js";
export default {
  data() {
    // 验证规范 ---- 开始 自定义的验证格式
    // 手机号
    var checkMobile = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("手机号不能为空"));
      } else if (!/^[0-9_]{1,}$/.test(value)) {
        return callback(new Error("请输入数字"));
      } else if (value.length != 11) {
        return callback(new Error("请输入11位手机号"));
      }else{
        return callback();
      }
    };
    // 身份证
    var checkIdCard = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("手机号不能为空"));
      } else if (!/^[A-Za-z0-9]+$/.test(value)) {
        return callback(new Error("请输入字母或数字"));
      } else if (value.length != 18) {
        return callback(new Error("请输入18位身份证号"));
      }else{
        return callback();
      }
    };
    // 验证规范 ---- 结束
    return {
        isshow: false,
        isZTree: false,
        fullWidth: document.documentElement.clientWidth,
        fullHeight: document.documentElement.clientHeight,
        zTreeList: [], //树形列表
        selectOptions:{
            nationList:[],
            politicalStatus:[],
            professionGroup:[]
        },
        page: { // page组件需要数据
            totalPages: null,
            visiblePages: 15,
            currentPage: 0
        },
        // nation: '1',
        managermentCenterName : '请填写所属机构',
        userForm: {
            birthdate : '',
            degree : '',
            educational : '',
            email : '',
            graduationDate : '',
            graduationSchool : '',
            managermentCenter : '',
            name : '',
            nation : '',
            idcard :'',
            mobile :'',
            politicalStatus : '',
            profession : '',
            professionGroup : '',
            sex : 0,
            oldState: null,
            state : 1,
            workTime : '',
      },
      rules: {
        name: [
            { required: true, message: "请输入姓名", trigger: "blur" },
            { max: 50, message: "姓名不能超过50个字符", trigger: "blur" },
        ],
        // managermentCenterName: [
        //     { required: true, message: "请选择所属机构", trigger: "blur,change"}
        // ],
        idcard: [
            { required: true, message: "请输入身份证号", trigger: "blur" },
            { validator: checkIdCard, trigger: "blur" }
        ],
        mobile: [
            { required: true, message: "请输入电话", trigger: "blur" },
            { validator: checkMobile, trigger: "blur" }
        ],
        email: [
            { required: true, message: "请输入邮箱地址", trigger: "blur" },
            { type: "email", message: "请输入正确的邮箱地址", trigger: "blur,change" }
        ],
        educational:[
          { max: 50, message: "最高学历不能超过50个字符", trigger: "blur" },
        ],
        degree:[
          { max: 50, message: "学位不能超过50个字符", trigger: "blur" },
        ],
        graduationSchool:[
          { max: 50, message: "毕业学校不能超过50个字符", trigger: "blur" },
        ],
        profession:[
          { max: 50, message: "专业不能超过50个字符", trigger: "blur" },
        ],
      },
      defaultProps: {
        children: 'child',
           label: 'name'
      }
    };
  },
  mounted() {
    if(this.$route.query.id){
        //获取用户信息
        this.getUser();
        this.page.currentPage = this.$route.query.pageNum;
        this.page.visiblePages = this.$route.query.pageSize;
    }else{
        this.zTreeEdit();
    }
    //获取民族信息
    this.getNation();
    //获取政治面貌信息
    this.getPoliticalStatus();
    //获取政治面貌信息
    this.getProfessionGroup();

  },
  methods: {
    close() {
      //   路由跳转 用户管理的页面
      this.$router.push("/systems/user");
    },
    //获取民族的列表
    getNation(){
        let self = this;
        self.axios({
            method: "get",
            url: dictsTypesSubListUrl,
            params:{
            "type":'ethnic_group'
            }
        })
        .then(function(response) {
            if(response.data.success){
                self.selectOptions.nationList = response.data.data;
            }else{
                self.$message({
                    duration: 1000,
                    message: response.data.msg,
                    center: true,
                    type: "error"
                });
            }
        })
    },
    //获取政治面貌的列表
    getPoliticalStatus(){
        let self = this;
        self.axios({
            method: "get",
            url: dictsTypesSubListUrl,
            params:{
            "type":'politics_status'
            }
        })
        .then(function(response) {
            if(response.data.success){
                self.selectOptions.politicalStatus = response.data.data;
            }else{
                self.$message({
                    duration: 1000,
                    message: response.data.msg,
                    center: true,
                    type: "error"
                });
            }
        })
    },
    //显示树结构
    showTree(){
        this.isZTree = !this.isZTree;
    },
    //获取政治面貌的列表
    getProfessionGroup(){
        let self = this;
        self.axios({
            method: "get",
            url: api.professionGroup.queryAllList,
        })
        .then(function(response) {
            if(response.data.success){
                _.forEach(response.data.data,function(item){
                    item.value = item.value+"";
                })
               self.selectOptions.professionGroup = response.data.data;
            }else{
                self.$message({
                    duration: 1000,
                    message: response.data.msg,
                    center: true,
                    type: "error"
                });
            }
        })
    },
    zTreeEdit(){
        let self = this;
        var setting = {
            view: {
                dblClickExpand: false
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            callback:{
              //点击事件
              onClick: zTreeOnClick,
              onCheck: zTreeCheck,
            }
        };

        self.axios({
            method: "get",
            url: self.axios.defaults.baseURL + "/offices/tree"
        })
        .then(function(response) {
            var zNodes = [];
            zNodes = response.data.data;
            //用户机构名称
            if(self.managermentCenterName !== "请填写所属机构"){
                let item = self.getName(zNodes,self.managermentCenterName);
                console.log(item);
                self.managermentCenterName = item.name;
                $(".textcol").css({"color":"#5a5e66"});
            }
            if(self.types == 'add'){
                var parentItem = self.getName(zNodes,self.orgInf.parentId);
                self.parentName = parentItem.name;
            }
            // 初始化树形结构
            $.fn.zTree.init($("#orgTree1"), setting, zNodes);
        })

        function zTreeOnClick(e, treeId, treeNode) {
            var treeObj = $.fn.zTree.getZTreeObj(treeId);
            var node = treeObj.getNodeByTId(treeNode.tId);
            self.userForm.managermentCenter = node.id;
            self.managermentCenterName = node.name;
            $(".textcol").css({"color":"#5a5e66"});
            self.hideMenu();
        };
        // 定义勾选事件
        function zTreeCheck(event, treeId, treeNode) {
            var treeObj = $.fn.zTree.getZTreeObj(treeId);
            var node = treeObj.getNodeByTId(treeNode.tId);
            self.managermentCenterName = node.name
            self.userForm.managermentCenter = node.id
            self.isZTree = !self.isZTree;
        };
    },
    onBodyDown(event) {
        let self = this;
        if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || event.target.id == "thrTree1" || $(event.target).parents("#thrTree1").length>0)) {
            self.hideMenu();
        }
    },
    showMenu() {
        let self = this;
        var cityObj = $("#thrTree1");
        var cityOffset = $("#thrTree1").offset();
        $("#thrTree1").css({left:cityOffset.left + "px", top:cityOffset.top + cityObj.outerHeight() + "px"}).slideDown("fast");

        $("body").bind("mousedown", self.onBodyDown);
        return false;
    },
    hideMenu() {
        let self = this;
        $("#thrTree1").fadeOut("fast");
        $("body").unbind("mousedown", self.onBodyDown);
        return false;
    },
    //显示树结构
    showTree(){
        this.isZTree = !this.isZTree;
    },
    getUserAll(){
        let self = this;
        // 发送请求
        self.axios({
            method: "get",
            url: api.userAllListUrl
        })
        .then(function(response) {
            if(response.data.success){
                self.options.leaderUserName = response.data.data;
            }else{
                // 操作失败
                self.$message({
                    message: response.data.msg,
                    type:'error',
                    center: true
                });
            }
        })
    },
    putUserArr(params){
        let self = this;
        let nameStr = '';
        var userArr = [];
        _.forEach(params,function(item,index){
            let userItem = {};
            userItem.id = item.id;
            userItem.name = item.name;
            userArr.push(userItem);

            //显示名字
            nameStr = nameStr + item.name + ','
        })
        this.leaderUserName = userArr;
        this.orgInf.leaderUserName = nameStr;
    },
    //  返回对象
    getName(json, id) {
        for (var i = 0; i < json.length; i++) {
            var model = json[i];
            if (model.id == id) {
                return model;
            }
            if (model.child != null && model.child.length > 0) {
                var name = this.getName(model.child, id);
                if (name != null) {
                    return name;
                }
            }
        }
        return null;
    },
    // 获取用户信息
    getUser() {
        let ID = this.$route.query.id;
        let self = this;

        if (ID) {
            //用户编辑状态
            self.axios({
                method: "get",
                url: getUserUrl + ID
            })
            .then(function(response) {
                if(response.data.success){

                    self.managermentCenterName = response.data.data.managermentCenter;
                    self.userForm = JSON.parse(JSON.stringify(response.data.data));
                    for(var key in self.userForm){
                        self.userForm[key] = response.data.data[key];
                    };
                    // 获得树形列表
                    self.zTreeEdit();

                    //转数字

                    self.userForm.sex = self.userForm.sex;
                    self.userForm.state = parseInt(self.userForm.state?self.userForm.state:'');
                    // 转字符串
                    self.userForm.professionGroup = parseInt(self.userForm.professionGroup);
                    self.userForm.nation = (self.userForm.nation? self.userForm.nation :'') + '';
                    self.userForm.politicalStatus = (self.userForm.politicalStatus? self.userForm.politicalStatus :'') + '';
                    self.oldState = self.userForm.state;
                }else{
                    self.$message({
                        duration: 1000,
                        message: response.data.msg,
                        center: true,
                        type: "error"
                    });
                }
            })
        }
    },
    //编辑 完成的  确定 提交
    addSubmit(formName,event) {
        this.$refs[formName].validate(valid => {
            if (valid) {
                let ID = this.$route.query.id;
                let self = this;
                // 定义当前地址与提交内容
                let currentUrl = "";
                let currentData = "";
                let currentMethod = "";

                if (ID) {
                    //用户管理 --- 编辑  ||   组织结构---用户编辑
                    currentMethod = "put";
                    currentUrl = usersHandleUrl + ID + "?oldState=" + self.oldState;
                } else {
                    //  添加用户
                    currentMethod = "post";
                    currentUrl = userInsertUrl;
                }

                self.userForm.nation = (self.userForm.nation == "undefined") ? '' : self.userForm.nation;
                self.userForm.politicalStatus = (self.userForm.politicalStatus == "undefined") ? '' : self.userForm.politicalStatus;
                if(self.managermentCenterName){
                    // 编辑时
                    // 添加新用户时
                    self.axios({
                        method: currentMethod,
                        url: currentUrl,
                        data: self.userForm
                    })
                    .then(function(response) {
                        if(response.data.success){
                            self.$message({
                                duration:1000,
                                message: response.data.msg,
                                center: true,
                                type:'success',
                                onClose:function(){
                                    if (ID) {
                                        self.$router.push({
                                            path: '/systems/user?pageNum=' + self.page.currentPage + '&pageSize=' + self.page.visiblePages,
                                        })
                                    } else {
                                        self.$router.push("/systems/user");
                                    }

                                }
                            });
                        }else{
                            self.$message({
                                duration:1000,
                                message: response.data.msg,
                                center: true,
                                type:'error'
                            });
                        }
                    })
                }else{
                    $(".org_box").addClass('is-error');
                    $(".org_box .el-form-item__error").css({"display": 'block'});
                    self.$message({
                        duration:1000,
                        message: "请选择该用户所属机构！",
                        center: true,
                        type:'error'
                    });
                }
            } else {
          return false;
        }
      });
    },
    // 树结构点击
    handleCheckChange(data, checked, indeterminate) {
        if(checked == true && indeterminate == false){
            this.userForm.managermentCenter = data.id;
            this.managermentCenterName = data.name;
            this.isZTree = false;
        }
    },
    //  返回对象
    getName(json, id) {
        for (var i = 0; i < json.length; i++) {
            var model = json[i];
            if (model.id == id) {
                return model;
            }
            if (model.child != null && model.child.length > 0) {
                var name = this.getName(model.child, id);
                if (name != null) {
                    return name;
                }
            }
        }
        return null;
    },
    // 重置
    userResetQuery(){
        let ID = this.$route.query.id;
        let self = this;
        if(ID){
            self.getUser();
        }else{
            for(var key in this.userForm){
                this.userForm[key] = null;
            };
        }
    },
    //返回上一层
    goBack(){
        // console.log(this.$route.query.id);
        let self = this;

        if(self.$route.query.id) {
            self.$router.push({
                path: '/systems/user?pageNum=' + self.page.currentPage + '&pageSize=' + self.page.visiblePages,
            })
        } else {
            self.$router.push("/systems/user");
        }
        // this.$router.go(-1);
    }
  },
  components: {}
};
</script>
<style scoped>
    #thrTree{position:absolute;top:20px;left:0;z-index:9;overflow:auto;margin-top:15px;padding:5px;width:200px;/* max-height:200px; */border:1px solid #ccc;border-radius:4px;background:#fff;}
    .UserBody .reti{width:135px;}
    .goBack{text-align:right;}
    .user_edit_box .el-input,.user_edit_box .el-select{width:100%;}
    .components_edit .el-input,.user_edit_box .el-input.el-input--suffix{width:178px!important;}
    .model_ct{width: 100%; position: absolute; top: 33px ;left:0; background: #FFF; z-index: 10; }
    #thrTree1{ padding: 10px; /* max-height:200px; */ overflow-y: auto; border-radius: 4px; border: 1px solid #dedede;}
    .textcol{position: relative;top: -1px; line-height: 24px; color: #b4bccc;}
    .is-error .el-input__inner{border-color:#fa5555;}
</style>
